from config import *
import requests
import json,urllib.parse,psutil,os,openpyxl

def add_query_parameters(base_url, params):
    """
    添加查询参数到链接中，保留原始查询参数。

    Args:
        base_url (str): 基本链接。
        params (dict): 包含参数名称和值的字典。

    Returns:
        str: 包含查询参数的新链接。
    """
    # 解析基本链接以获取其查询字符串部分
    parsed_url = urllib.parse.urlparse(base_url)

    # 解析现有的查询参数
    existing_query_params = urllib.parse.parse_qs(parsed_url.query)

    # 将新参数添加到现有参数中
    existing_query_params.update(params)

    # 构建新的查询字符串
    new_query_string = urllib.parse.urlencode(existing_query_params, doseq=True)

    # 用新的查询字符串替换现有的查询字符串
    new_parsed_url = parsed_url._replace(query=new_query_string)

    # 从新的解析链接中获取最终的链接字符串
    new_url = urllib.parse.urlunparse(new_parsed_url)

    return new_url

async def repeat_goto(page,url,t=3):

    for jj in range(t):
        try:
            await page.goto(url)
            break
        except Exception as e:
            print(f'浏览器goto错误 => {e},正在重试{jj+1}次')

def killjc(jcname):
    pids = psutil.pids()
    for pid in pids:
        try:
            p = psutil.Process(pid)
            # print('pid-%s,pname-%s' % (pid, p.name()))
            if p.name() == f'{jcname}':
                print(f'关闭{pid} => {p.name()}')
                cmd = f'taskkill /F /IM {jcname}'
                os.system(cmd)

        except Exception as e:
            pass
    
async def page_scroll_bottom(page,w,h,flag=False):
    for jj in range(3):
        await page.mouse.move(w-10,20)
        await page.mouse.down()
        await page.mouse.move(w-10,h+50, {'steps': 20})
        await page.mouse.up()
        await page.waitFor(1000)
        els=await page.xpath('//div[@data-sqe="item"]/a[1]')
        if not flag:
            if len(els)>=60:
                break
        else:
            if len(els)>=0:
                break

def delempty2(fpath):
    wb=openpyxl.load_workbook(fpath)
    ws=wb[wb.sheetnames[0]]

    while True:
        if ws.cell(ws.max_row,1).value:
            break
        ws.delete_rows(ws.max_row)
    #print(f'删除空白行后,剩余{ws.max_row}')

    while True:
        if ws.cell(1,ws.max_column).value:
            break
        ws.delete_cols(ws.max_column)
    #print(f'删除空白列后,剩余{ws.max_column}')
    # wb.save(fpath)
    return ws

def getDictDatasByEecel(fpath):
    ws=delempty2(fpath)

    datas=[]    
    headers=[ws.cell(1,col).value for col in range(1,ws.max_column+1)]
    for row in range(2,ws.max_row+1):

        currow={}
        for col in range(1,ws.max_column+1):
            curtitle=headers[col-1]
            currow[curtitle]=ws.cell(row,col).value
        datas.append(currow)

    return datas

session=requests.session()
session.headers={
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': DeepSeek_Auth
}

